package com.sunshine.wrongquestionset.activity.exercise

import android.annotation.SuppressLint
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.google.android.material.snackbar.Snackbar
import com.google.android.material.textfield.TextInputEditText
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.wanglu.photoviewerlibrary.PhotoViewer
import com.zzhoujay.markdown.MarkDown
import com.zzhoujay.richtext.ImageHolder
import com.zzhoujay.richtext.RichText
import com.zzhoujay.richtext.RichType
import com.zzhoujay.richtext.callback.OnImageClickListener
import es.dmoral.toasty.Toasty
import kotlinx.android.synthetic.main.fragment_exercise.*
import kotlinx.android.synthetic.main.fragment_exercise_score.*
import kotlinx.android.synthetic.main.fragment_exercise_score.textView_title_content

class ExerciseScoreFragment : Fragment() {

    private var positionId: Int = -1
    private var questionId: Int = -1
    private lateinit var viewModel: ExerciseViewModel
    private lateinit var questionEntity: QuestionEntity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            positionId = it.getInt(ARG_PARAM_POSITION_ID)
            questionId = it.getInt(ARG_PARAM_QUESTION_ID)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_exercise_score, container, false)
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)).get(ExerciseViewModel::class.java)

        questionEntity = ExerciseScoreActivity.getQuestionList()!![positionId]

        initView()

        textView_score.text = "本题共${questionEntity.score}分，请给自己打个分吧"

        edit_score.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                var score: String? = s?.let { s.toString() }

                if (score.isNullOrBlank()) {
                    ExerciseScoreActivity.removeScore(positionId)
                }
                else {
                    //如果有正负号，就去掉
                    if (score.contains("+") || score.contains("-")) {
                        score = score.replace("+", "").replace("-", "")
                        //edit_score.setText(score)
                    }

                    try {
                        if (score.toFloat() > ExerciseScoreActivity.getQuestionList()?.get(positionId)?.score?:0.0f) {
                            Snackbar.make(root, "哎呀，好像比这道题的满分还多了呢", Snackbar.LENGTH_SHORT).show()
                            //出错就将之前的也移除掉
                            ExerciseScoreActivity.removeScore(positionId)
                        } else {
                            ExerciseScoreActivity.addScore(positionId, questionId, score.toFloat(), questionEntity.score)
                        }
                    }catch (e: Exception) {
                        //Snackbar.make(root, "数字输入出现问题了", Snackbar.LENGTH_SHORT).show()
                    }


                }

                (requireActivity() as ExerciseScoreActivity).notifyCardFragmentDataSetChanged()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })
    }

    private fun initView() {
//        textView_title_content.post {
//            Thread {
//                val spanned = MarkDown.fromMarkdown(questionEntity.titlePath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, textView_title_content)
//
//                textView_title_content.post {
//                    textView_title_content.text = spanned
//                }
//            }.start()
//        }

        RichText
            .from(questionEntity.titlePath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .imageClick(object : OnImageClickListener {
                override fun imageClicked(imageUrls: MutableList<String>?, position: Int) {
                    if (imageUrls.isNullOrEmpty()) return
                    PhotoViewer
                        .setClickSingleImg(imageUrls[position], ImageView(requireContext()))   //因为本框架不参与加载图片，所以还是要写回调方法
                        .setShowImageViewInterface(object : PhotoViewer.ShowImageViewInterface {
                            override fun show(iv: ImageView, url: String) {
                                Glide.with(iv.context).load(url).into(iv)
                            }
                        })
                        .start(this@ExerciseScoreFragment)
                }
            })
            .into(textView_title_content)

//        textView_answer_content.post {
//            Thread {
//                val spanned = MarkDown.fromMarkdown(questionEntity.answerPath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, textView_answer_content)
//
//                textView_answer_content.post {
//                    textView_answer_content.text = spanned
//                }
//            }.start()
//        }

        RichText
            .from(questionEntity.answerPath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .imageClick(object : OnImageClickListener {
                override fun imageClicked(imageUrls: MutableList<String>?, position: Int) {
                    if (imageUrls.isNullOrEmpty()) return
                    PhotoViewer
                        .setClickSingleImg(imageUrls[position], ImageView(requireContext()))   //因为本框架不参与加载图片，所以还是要写回调方法
                        .setShowImageViewInterface(object : PhotoViewer.ShowImageViewInterface {
                            override fun show(iv: ImageView, url: String) {
                                Glide.with(iv.context).load(url).into(iv)
                            }
                        })
                        .start(this@ExerciseScoreFragment)
                }
            })
            .into(textView_answer_content)

        //位置+1
        val myAnswerPath = ExerciseScoreActivity.getAnswerMap()[positionId + 1]?.resultPath?:""
        //如果答案为空不准判分
        if (myAnswerPath.isBlank()) {
            edit_score.isEnabled = false
            edit_score.setText("0分，因为你没有作答")
            ExerciseScoreActivity.addScore(positionId, questionId, 0.0f, ExerciseScoreActivity.getQuestionList()!![positionId].score)
            (requireActivity() as ExerciseScoreActivity).notifyCardFragmentDataSetChanged()
        }

        RichText
            .from(myAnswerPath.replace("\n", "\n\n"))
            .type(RichType.markdown)
            .scaleType(ImageHolder.ScaleType.fit_auto)
            .imageClick(object : OnImageClickListener {
                override fun imageClicked(imageUrls: MutableList<String>?, position: Int) {
                    if (imageUrls.isNullOrEmpty()) return
                    PhotoViewer
                        .setClickSingleImg(imageUrls[position], ImageView(requireContext()))   //因为本框架不参与加载图片，所以还是要写回调方法
                        .setShowImageViewInterface(object : PhotoViewer.ShowImageViewInterface {
                            override fun show(iv: ImageView, url: String) {
                                Glide.with(iv.context).load(url).into(iv)
                            }
                        })
                        .start(this@ExerciseScoreFragment)
                }
            })
            .into(textView_my_answer_content)
//
//        textView_my_answer_content.post {
//
//            Thread {
//                val spanned = MarkDown.fromMarkdown(myAnswerPath.replace("\n", "\n\n"), { source ->
//                    try {
//                        //主线程执行，效果不是很好
//                        val drawable = Drawable.createFromPath(source)
//                        drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                        drawable
//                    }catch (e: Exception) {
//                        //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                        null
//                    }
//                }, textView_my_answer_content)
//
//                textView_my_answer_content.post {
//                    textView_my_answer_content.text = spanned
//                }
//            }.start()
//
//
//        }
    }

    companion object {
        private const val ARG_PARAM_QUESTION_ID = "question"
        private const val ARG_PARAM_POSITION_ID = "position"
        @JvmStatic
        fun newInstance(positionId: Int, questionId: Int) =
            ExerciseScoreFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_PARAM_POSITION_ID, positionId)
                    putInt(ARG_PARAM_QUESTION_ID, questionId)
                }
            }
    }
}